import { useParams } from "react-router-dom";
import { getQuestionService } from "../services/question";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { resetComponents } from "@/store/componentsReducer";
import { resetPageInfo } from "@/store/pageInfoReducer";

const useLoadQuestionData = () => {
  const { id = "" } = useParams();
  const dispatch = useDispatch();

  const { run, loading, error, data } = useRequest(
    async (id: string) => {
      if (!id) throw new Error("没有问卷 id");
      const data = await getQuestionService(id);
      return data;
    },
    {
      manual: true,
    }
  );

  useEffect(() => {
    run(id);
  }, [id]);

  useEffect(() => {
    if (!data) return;

    const {
      title = "",
      componentList = [],
      desc = "",
      css = "",
      js = "",
      isPublished = false,
    } = data;
    // 获取默认的 selectedId
    let selectedId = "";
    if (componentList.length > 0) {
      selectedId = componentList[0].fe_id;
    }

    // selectedId 不能置空，先获取再传入
    dispatch(resetComponents({ componentList, selectedId }));

    // 把 pageInfo 存储的 redux store
    dispatch(
      resetPageInfo({
        title,
        desc,
        css,
        js,
        isPublished,
      })
    );
  }, [data]);

  return { loading, error };
};

export default useLoadQuestionData;
